package br.com.android.watcher;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;

import android.os.Handler;
import android.os.Message;

public class DataFetcher extends Thread {
	private ArrayList<Toon> aa;
	private Handler h;
	private int size;
	
	public DataFetcher(Handler h, ArrayList<Toon> aa, int s){
		this.aa = aa;
		this.h = h;	
		this.size = s;
	}
	public DataFetcher(){
		this.aa = null;
		this.h = null;
		this.size = 0;
	}
	public synchronized void run() {
		Toon t;
		Message msg; 
		for(int i=0;i<this.size;i++){
			t = updateToonScore(this.aa.get(i));
			//Log.v("Watcher Act","Data Fetcher " + i + " fetching data for: " +t.getName() + " score:" + t.getScore());
			msg = this.h.obtainMessage(this.size, i, t.getScore());
			this.h.sendMessage(msg);
		}

		
	}
	
	static public Toon updateToonScore(Toon t){
			String score = new String();
			try{ 
			URL url = new URL("http://us.battle.net/wow/en/character/" + t.getRealm() + "/" + t.getName() + "/achievement");
			BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));  
			String singleLine = null;  
			while ( (singleLine = reader.readLine()) != null)
				if(singleLine.contains("class=\"achievement-points\""))
					score = reader.readLine().trim();
					System.out.println(score);
					t.setScore(Integer.valueOf(score));
			}
			catch(Exception e){
				//Log.v("Watcher Act", e.getMessage());
			}
		return t;
			
	}
/*	private void updateToonInfo(){
				String name, level, race, classe;
				try{
				URL url = new URL("http://www.wowarmory.com/character-sheet.xml?r=");
				///URL url = new URL("http://www.wowarmory.com/character-sheet.xml?r=" + t.getRealm() + "&cn=" + t.getName());
		  
				BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));  
				String singleLine = null;  
				while ( (singleLine = reader.readLine()) != null)

					if(singleLine.contains("char-profile_name")){
						singleLine = singleLine.substring(singleLine.indexOf(">"));
						name = singleLine.substring(1,singleLine.indexOf("<"));
						singleLine = singleLine.substring(singleLine.indexOf("<span>")+5);
						level = singleLine.substring(1,singleLine.indexOf("<"));
						singleLine = singleLine.substring(singleLine.indexOf(";"));
						System.err.println(singleLine);
						race = singleLine.substring(1,singleLine.indexOf("&nbsp;"));
						singleLine = singleLine.substring(singleLine.indexOf(";",1));
						classe = singleLine.substring(1,singleLine.indexOf("</span>"));
						
		///				t.setName(name);
			///			t.setInfo(classe, race, level);
						
						

					}
					
					
				reader.close();
				}
				catch(Exception e){
					Log.v("Watcher Act", e.getMessage());
				}
			return;
		}
	*/
}
